﻿using UnityEngine;

namespace CGF
{
    public class ScaleLoop : MonoBehaviour
    {
        public bool randomStart;
        public float wait;
        public Vector3 minScale = new Vector3(0.9f, 0.9f, 0.9f);
        public Vector3 maxScale = new Vector3(1.1f, 1.1f, 1.1f);
        public float speed = 5;
        float scaleX, scaleY, scaleZ, r, delay;
        bool isStop, isPause;

        void Awake()
        {
            if (randomStart)
            {
                r = Random.Range(0f, Mathf.PI * 2f);
            }
        }

        void Update()
        {
            if (isPause) return;

            if (wait > 0f)
            {
                if (delay > 0f)
                {
                    delay -= Time.deltaTime;
                }
                else
                {
                    r += speed * Time.deltaTime;
                    if (r >= Mathf.PI * 2f)
                    {
                        r = 0f;
                        delay = wait;
                        if (isStop)
                        {
                            isPause = true;
                        }
                    }
                }
            }
            else
            {
                r += speed * Time.deltaTime;
                if (r >= Mathf.PI * 2f)
                {
                    r = 0f;
                    if (isStop)
                    {
                        isPause = true;
                    }
                }
            }
            float sin = Mathf.Sin(r) * 0.5f + 0.5f;
            scaleX = minScale.x + sin * (maxScale.x - minScale.x);
            scaleY = minScale.y + sin * (maxScale.y - minScale.y);
            scaleZ = minScale.z + sin * (maxScale.z - minScale.z);
            transform.localScale = new Vector3(scaleX, scaleY, scaleZ);
        }

        public void StartLoop()
        {
            isStop = false;
            isPause = false;
        }

        public void StopLoop()
        {
            isStop = true;
        }

        public void PauseLoop()
        {
            isPause = true;
        }
    }
}